<template>
  <el-form label-width="100" :model="spuParams">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input v-model="spuParams.spuName" placeholder="请输入SPU名称"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select class="select" v-model="spuParams.tmId" placeholder="请输入SPU品牌">
        <el-option v-for="item in allTrademarkArr" :key="item.id" :label="item.tmName" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述" prop="description">
      <el-input type="textarea" v-model="spuParams.description" placeholder="请输入SPU描述"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片" prop="logoUrl">
      <el-upload
        v-model:file-list="spuImageArr"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-upload="beforeImageUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogImageVisible">
        <img w-full :src="dialogImageUrl" alt="" class="previewImg" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        class="select"
        v-model="saleAttrIdAndValueName"
        :placeholder="unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : '无'"
      >
        <el-option v-for="item in unSelectSaleAttr" :key="item.id" :label="item.name" :value="`${item.id}:${item.name}`"></el-option>
      </el-select>
      <el-button type="primary" icon="Plus" :disabled="saleAttrIdAndValueName ? false : true" @click="addSpuSaleAttr">添加属性</el-button>
      <el-table :data="spuSaleAttrArr" class="el-table" border>
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="saleAttrName" label="销售属性名称" width="120" align="center"></el-table-column>
        <el-table-column label="销售属性值" align="center">
          <template #default="{ row, $index }">
            <el-tag
              class="elTag"
              type="primary"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              closable
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              class="elInputAttrValue"
              ref="InputEle"
              v-model="row.saleAttrValue"
              v-if="row.flag"
              size="small"
              placeholder="请输入属性值"
              @keyup.enter="toLook(row)"
              @blur="toLook(row)"
            />
            <el-button v-else type="primary" circle icon="Plus" size="small" @click="addSpuSaleAttrValue(row)"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="60" align="center">
          <template #default="{ row, $index }">
            <el-button type="danger" circle icon="Delete" size="small" @click="deleteSpuSaleAttr(row, $index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="confirm">保存</el-button>
      <el-button type="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {
  AllTrademark,
  HasSaleAttr,
  HasSaleAttrResponseData,
  SaleAttr,
  SaleAttrResponseData,
  SaleAttrValue,
  SpuData,
  SpuHasImage,
  SpuImage,
  Trademark,
} from '@/api/product/spu/types';

// 属性值输入框的元素ref
const InputEle = ref();
// 选中的销售属性的id和名称
const saleAttrIdAndValueName = ref<string>('');
// 图片预览弹窗的图片地址
const dialogImageUrl = ref<string>('');
// 显示图片预览弹窗
const dialogImageVisible = ref<boolean>(false);
// 所有品牌数组
const allTrademarkArr = ref<Trademark[]>([]);
// 这个spu所有图片数组
const spuImageArr = ref<SpuImage[]>([]);
// 这个spu拥有的属性
const spuSaleAttrArr = ref<SaleAttr[]>([]);
// 所有的属性
const allSaleAttrArr = ref<HasSaleAttr[]>([]);
// spu的参数
const spuParams = reactive<SpuData>({
  spuName: '',
  category3Id: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
});
// 计算出没有选中的销售属性
const unSelectSaleAttr = computed(() => {
  const usSelectArr = allSaleAttrArr.value.filter((item) => {
    return spuSaleAttrArr.value.every((item1) => {
      return item.name !== item1.saleAttrName;
    });
  });
  return usSelectArr;
});
// 接收父组件传递过来的方法和参数
const emit = defineEmits(['changeSecene']);
// 对外暴露的更新spu加载数据的方法
const initHasSpuData = async (spu: SpuData) => {
  Object.assign(spuParams, spu);

  // 获取所有品牌数据
  const result1: AllTrademark = await reqGetAllTrademark();
  if (result1.code === 200) {
    allTrademarkArr.value = result1.data;
  }
  // 获取某个spu所有的图片
  const result2: SpuHasImage = await reqGetSpuImageList(spu.id as number);
  if (result2.code === 200) {
    spuImageArr.value = result2.data.map((item) => ({ name: item.imgName, url: item.imgUrl }));
  }
  // 获取某个spu的销售属性
  const result3: SaleAttrResponseData = await reqGetSpuSaleAttrList(spu.id as number);
  if (result3.code === 200) {
    spuSaleAttrArr.value = result3.data;
  }
  // 获取所有的销售属性
  const result4: HasSaleAttrResponseData = await reqGetSaleAttrList();
  if (result4.code === 200) {
    allSaleAttrArr.value = result4.data;
  }
};
// 对外暴露的更新spu加载数据的方法
const initAddSpuData = async (c3Id: number | string) => {
  Object.assign(spuParams, {
    spuName: '',
    category3Id: c3Id,
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  });

  spuImageArr.value = [];
  spuSaleAttrArr.value = [];
  saleAttrIdAndValueName.value = '';

  // 获取所有品牌数据
  const result1: AllTrademark = await reqGetAllTrademark();
  if (result1.code === 200) {
    allTrademarkArr.value = result1.data;
  }
  // 获取所有的销售属性
  const result4: HasSaleAttrResponseData = await reqGetSaleAttrList();
  if (result4.code === 200) {
    allSaleAttrArr.value = result4.data;
  }
};
// 对外暴露
defineExpose({ initHasSpuData, initAddSpuData });

//上传图片之前判断格式和大小是否符合要求
const beforeImageUpload = (file: any) => {
  if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
    ElMessage.error('头像图片格式必须是 JPG | PNG | GIF ！');
    return false;
  } else if (file.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过2MB！');
    return false;
  }
  return true;
};
// 点击图片列表触发预览弹窗
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogImageVisible.value = true;
};
//添加spu销售属性
const addSpuSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':');
  const newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  spuSaleAttrArr.value.push(newSaleAttr);
  saleAttrIdAndValueName.value = '';
};
//添加spu销售属性值
const addSpuSaleAttrValue = (row: SaleAttr) => {
  row.flag = true;
  row.saleAttrValue = '';
  nextTick(() => {
    InputEle.value.input.focus();
  });
};
//删除spu的销售属性
const deleteSpuSaleAttr = (row: SaleAttr) => {
  spuSaleAttrArr.value.splice(spuSaleAttrArr.value.indexOf(row), 1);
};
// 完成销售属性值输入确认
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row;
  const newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  };

  if ((saleAttrValue as string).trim() === '') {
    ElMessage.error('属性值不能为空');
    return;
  }
  const repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === saleAttrValue;
  });
  if (repeat) {
    ElMessage.error('属性值不能重复');
    return;
  }

  row.spuSaleAttrValueList.push(newSaleAttrValue);
  row.flag = false;
};
// 确认添加或者更新
const confirm = async () => {
  spuParams.spuImageList = spuImageArr.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  spuParams.spuSaleAttrList = spuSaleAttrArr.value;

  const result: any = await reqAddOrUpdateSPU(spuParams);
  if (result.code === 200) {
    emit('changeSecene', {
      flag: 0,
      params: spuParams.id ? 'update' : 'add',
    });
    ElMessage.success(spuParams.id ? '更新成功' : '添加成功');
  } else {
    ElMessage.error(spuParams.id ? '更新失败' : '添加失败');
  }
};
// 取消添加或者更新
const cancel = () => {
  emit('changeSecene', {
    flag: 0,
    params: 'update',
  });
};
</script>

<style lang="scss" scoped>
.select {
  width: 240px;
  margin-right: 20px;
}
.el-table {
  margin-top: 20px;
}
.previewImg {
  width: 100%;
  height: 100%;
}
.elTag {
  margin-right: 5px;
}
.elInputAttrValue {
  width: 100px;
}
</style>
